<script setup>
import {h, onMounted, ref, resolveDirective, withDirectives} from 'vue'
import {NButton, NInput, NPopconfirm, NSelect, NTag} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudTable from '@/components/table/CrudTable.vue'

import { useCRUD } from '@/composables'
import api from '@/api'
import {getToken, renderIcon} from "@/utils";
import axios from "axios";

defineOptions({ name: '下载中心' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const base_path = import.meta.env.VITE_BASE

const {
  modalVisible,
  modalTitle,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '下载中心',
  initForm: {
    args: {
      ping_sleep: 1,
      ping_threshold: 500,
      agent_data_check_threshold: 2,
      agent_incoming_traffic_threshold: 30,
      before_start_clean_sleep: 2,
      before_stop_disposal_sleep: 20,
    },
  },
  doCreate: api.createHostMonitor,
  doUpdate: api.updateHostMonitor,
  doDelete: api.deleteHostMonitor,
  refresh: () => $table.value?.handleSearch(),
})

onMounted(() => {
  $table.value?.handleSearch()
})

function formatTimestamp(timestamp) {
  const date = new Date(timestamp)

  const pad = (num) => num.toString().padStart(2, '0')

  const year = date.getFullYear()
  const month = pad(date.getMonth() + 1) // 月份从0开始，所以需要+1
  const day = pad(date.getDate())
  const hours = pad(date.getHours())
  const minutes = pad(date.getMinutes())
  const seconds = pad(date.getSeconds())

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 获取当天的开始时间的时间戳
function getStartOfDayTimestamp() {
  const now = new Date()
  now.setHours(0, 0, 0, 0) // 将小时、分钟、秒和毫秒都设置为0
  return now.getTime()
}

// 获取当天的结束时间的时间戳
function getEndOfDayTimestamp() {
  const now = new Date()
  now.setHours(23, 59, 59, 999) // 将小时设置为23，分钟设置为59，秒设置为59，毫秒设置为999
  return now.getTime()
}

// 示例使用
const startOfDayTimestamp = getStartOfDayTimestamp()
const endOfDayTimestamp = getEndOfDayTimestamp()

const datetimeRange = ref([startOfDayTimestamp, endOfDayTimestamp])
const handleDateRangeChange = (value) => {
  queryItems.value.start_time = formatTimestamp(value[0])
  queryItems.value.end_time = formatTimestamp(value[1])
}

const data = reactive({
  token: getToken(),
});


async function on_download(row) {
  if (!row.id) return
  row.publishing = true
  row.state = row.state === false
  row.publishing = false
  try {
    let headers = { token: data.token }
    let data_p = { data_id: row.id }
    const response = await axios.get(base_path+'api/system/downloads/down', {
              responseType: 'blob', // 重要：指定响应类型为 blob
              headers:headers,
              params:data_p
            });
            // 创建一个新的 URL 对象
            const url = window.URL.createObjectURL(new Blob([response.data]));
            // 创建一个新的链接元素
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', row.name+'.xlsx'); // 指定下载文件的名称
            // 模拟点击下载
            document.body.appendChild(link);
            link.click();
            // 清理 URL 对象
            window.URL.revokeObjectURL(url);

    $message?.success("已下载")
    $table.value?.handlerefresh()
  } catch (err) {
    // 有异常恢复原来的状态
    row.state = row.state === false
  } finally {
    row.publishing = false
  }
}

const columns = [
  {
    title: 'ID',
    key: 'id',
    width: '100',
    align: 'center',
    ellipsis: { tooltip: true },
  },{
    title: '文件名称',
    key: 'name',
    width: 'auto',
    align: 'left',
    ellipsis: { tooltip: true },
  },
     {
    title: '生成时间',
    key: 'created_at',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
  },
  // {
  //   title: '下载次数',
  //   key: 'count',
  //   width: 'auto',
  //   align: 'center',
  //   ellipsis: { tooltip: true },
  // },
    {
    title: '下载状态',
    key: 'state',
    width: 'auto',
    align: 'center',
    ellipsis: { tooltip: true },
      render(row) {
      return h(
        NTag,
        { type: row.state===0 ? 'primary' : 'success',bordered:false, style: { margin: '2px 3px' } },
        { default: () => (row.state===0 ? '未下载' : '已下载') }
      )
    },
  },
      {
    title: '操作',
    key: 'actions',
    width: 180,
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        withDirectives(
          h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              style: 'margin-right: 8px;',
              onClick: () => {
                 on_download(row)
              },
            },
            {
              default: () => '下载',
              icon: renderIcon('material-symbols:download', { size: 16 }),
            }
          ),
          []
        )
      ]
    },
  },

]
</script>

<template>
  <!-- 业务页面 -->
  <CommonPage>
    <!-- 表格 -->
    <CrudTable
      ref="$table"
      v-model:query-items="queryItems"
      :columns="columns"
      :get-data="api.getDownloadsList"
    >
      <template #queryBar>
        <QueryBarItem label="文件名" :label-width="60">
          <NInput v-model:value="queryItems.name" clearable type="text" placeholder="请输入文件名"
            @keypress.enter="$table?.handleSearch()" />
        </QueryBarItem>
        <QueryBarItem label="创建时间" :label-width="70">
          <NDatePicker
            v-model:value="datetimeRange"
            type="datetimerange"
            clearable
            placeholder="请选择时间范围"
            @update:value="handleDateRangeChange"
          />
        </QueryBarItem>
      </template>
    </CrudTable>
  </CommonPage>
</template>
